const Router = require('koa-router');
const awaitFs = require('await-fs');
const path = require('path');
const comm = require('../../libs/common');
let router = new Router();
let banner_table = 'banner_table';
router.get('/login',async ctx =>{
    await ctx.render('admin/login',{
        HTTP_ROOT: ctx.config.HTTP_ROOT,
        errmsg: ctx.query.errmsg
    })
});
router.post('/login',async ctx =>{
    const {HTTP_ROOT} = ctx.config;
    let {username,password} = ctx.request.fields;
    let admins = JSON.parse((await awaitFs.readFile(path.resolve(__dirname,'../../admins.json'))).toString());
    function findAdmin(username) {
        let a = null;
        admins.forEach(admin =>{
            if(admin.username == username){
                a = admin;
            }
        });
        return a;
    }
    let admin = findAdmin(username);
    if(!admin){
        ctx.redirect(`${HTTP_ROOT}/admin/login?errmsg=${encodeURIComponent('用户不存在')}`)
    }else if(admin.password != comm.md5(password)){
        ctx.redirect(`${HTTP_ROOT}/admin/login?errmsg=${encodeURIComponent('密码错误')}`)
    }else{
        ctx.session['admin']= username;
        ctx.redirect(`${HTTP_ROOT}/admin/`);
    }
});
router.all('*', async (ctx,next) =>{
    let {HTTP_ROOT} = ctx.config;
    if(ctx.session['admin']){
        await ctx.set('Access-Control-Allow-Origin', '*');
        await next();
    }else{
        //打印日志
        ctx.redirect(`${HTTP_ROOT}/admin/login`)
    }
});
router.get('/', async ctx =>{
    let {HTTP_ROOT} = ctx.config;
    ctx.redirect(`${HTTP_ROOT}/admin/banner`);
});
router.use('/banner',require('./banner'));
router.use('/article',require('./article'));
router.use('/catalog',require('./catalog'));

module.exports = router.routes();